package controllers

import (
	"GO_BACK/api/dbapi"
	"GO_BACK/api/logicapi"
	"GO_BACK/model/data"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type email struct {
	Email string
}

func SendEmailController(c *gin.Context) {
	var gestures *email
	c.BindJSON(&gestures)
	email := gestures.Email
	row := dbapi.Querybyemail(email)
	//判断当前email是否已经注册过，如果已经注册过了就不发验证码
	if row.Email == email {
		fmt.Println(row.Email)
		c.JSON(http.StatusOK, gin.H{
			"message": "发送验证码失败",
			"error":   "当前邮箱已经注册过了请更换未注册的邮箱",
		})
	} else {
		err, code := logicapi.SendEmail(email)
		fmt.Println(code)
		fmt.Println(email)
		db, _ := dbapi.PgDbConnect()
		vertify := &data.VerifyStruct{
			Email:       email,
			Vertifycode: code,
			Time:        time.Now(),
		}
		dbapi.PgDbCreate(vertify, db)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"message": "发送验证码失败",
				"error":   err,
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"message": "发送验证码成功",
				"code":    code,
			})
		}
	}

}
